<template>
  <div class="container">
    <a-card class="general-card">
      <!-- 搜索区域 -->
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="用户名称">
                  <a-input
                    v-model="searchForm.name"
                    placeholder="请输入用户名称"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="警号">
                  <a-input
                    v-model="searchForm.policeNum"
                    placeholder="请输入警号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="用户角色">
                  <a-select
                    v-model="searchForm.role"
                    :options="roleOptions"
                    placeholder="请选择角色"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="用户组织">
                  <a-tree-select
                    v-model="searchForm.group"
                    :data="orgTreeData"
                    placeholder="请选择组织"
                    allow-clear
                    :field-names="{
                      key: 'groupId',
                      title: 'groupName',
                      children: 'children',
                    }"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="科室">
                  <a-select
                    v-model="searchForm.dept"
                    :options="deptOptions"
                    placeholder="请选择科室"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
            <a-button @click="resetForm">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <!-- 工具栏 -->
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
            <a-button
              type="primary"
              status="danger"
              :disabled="false"
              @click="handleBatchDelete"
            >
              <template #icon>
                <icon-delete />
              </template>
              批量删除
            </a-button>
            <a-upload
              action="/api/user/import"
              :show-file-list="false"
              @success="handleImportSuccess"
            >
              <template #upload-button>
                <a-button>
                  <template #icon>
                    <icon-upload />
                  </template>
                  批量导入
                </a-button>
              </template>
            </a-upload>
          </a-space>
        </a-col>
      </a-row>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        row-key="userId"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #action="{ record }">
          <a-space>
            <a-button
              v-if="record.userId !== 1"
              type="text"
              size="small"
              @click="handleEdit(record)"
              >编辑</a-button
            >
            <a-button
              v-if="record.userId !== 1"
              type="text"
              size="small"
              status="danger"
              @click="handleDelete(record)"
              >删除</a-button
            >
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 弹窗：用户表单 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      :width="600"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="name" label="用户名称" required>
              <a-input v-model="formData.name" placeholder="请输入用户名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="iphone" label="手机号">
              <a-input v-model="formData.iphone" placeholder="请输入手机号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="policeNum" label="警号" required>
              <a-input
                v-model="formData.policeNum"
                placeholder="请输入警号"
                @blur="
                  () => validatePoliceNum(formData.policeNum, formData.userId)
                "
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="role" label="用户角色" required>
              <a-select
                v-model="formData.role"
                :options="roleOptions"
                placeholder="请选择角色"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="group" label="用户组织" required>
              <a-tree-select
                v-model="formData.group"
                :data="orgTreeData"
                placeholder="请选择组织"
                :field-names="{
                  key: 'groupId',
                  title: 'groupName',
                  children: 'children',
                }"
                allow-search
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="dept" label="科室" required>
              <a-select v-model="formData.dept" placeholder="请选择科室">
                <a-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :value="dept.id"
                >
                  {{ dept.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { Message, Modal, type FileItem } from "@arco-design/web-vue";
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  batchDeleteUsers,
  getDeptList,
  getOrgList,
  validUserByPoliceNum,
  type UserInfo,
  type UserQueryParams,
  type DeptInfo,
  type OrgInfo,
} from "@/api/user";
import { queryRoleList, type RoleInfo as RoleInfoRes } from "@/api/role";

// 响应式数据
const loading = ref(false);
const tableData = ref<UserInfo[]>([]);
const selectedRowKeys = ref<number[]>([]);
const formVisible = ref(false);
const formTitle = ref("新增用户");
const formRef = ref();

const rowSelection = {
  type: "checkbox",
  showCheckedAll: true,
  checkStrictly: true,
  onChange: (keys: (string | number)[]) => {
    selectedRowKeys.value = keys as number[];
  },
};
// 科室和组织架构数据
const deptList = ref<DeptInfo[]>([]);
const orgTreeData = ref<OrgInfo[]>([]);
const roleList = ref<RoleInfoRes[]>([]);

// 搜索表单
const searchForm = reactive<UserQueryParams>({
  pageNo: 1,
  pageSize: 10,
  name: "",
  policeNum: "",
  role: undefined,
  group: undefined,
  dept: undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 表单数据
const formData = reactive<UserInfo>({
  name: "",
  iphone: "",
  role: 3,
  policeNum: "",
  group: undefined,
  dept: undefined,
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: "请输入用户名称" }],
  iphone: [
    { required: true, message: "请输入手机号" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
  ],
  policeNum: [{ required: true, message: "请输入警号" }],
  role: [{ required: true, message: "请选择用户角色" }],
  group: [{ required: true, message: "请选择用户组织" }],
  dept: [{ required: true, message: "请选择科室" }],
};

// 角色选项
const roleOptions = computed(() => {
  return roleList.value.map((role) => ({
    label: role.roleName,
    value: role.roleId,
  }));
});

// 科室选项
const deptOptions = computed(() => {
  return deptList.value.map((dept) => ({
    label: dept.name,
    value: dept.id,
  }));
});

// 表格列配置
const columns = [
  { title: "用户ID", dataIndex: "userId" },
  { title: "用户名称", dataIndex: "name" },
  { title: "手机号", dataIndex: "iphone" },
  { title: "警号", dataIndex: "policeNum" },
  {
    title: "用户角色",
    dataIndex: "role",
    render: ({ record }) => {
      const role = roleOptions.value.find((r) => r.value === record.role);
      return role ? role.label : "未知角色";
    },
  },
  {
    title: "用户组织",
    dataIndex: "group",
    render: ({ record }) => getOrgName(record.group),
  },
  {
    title: "科室",
    dataIndex: "dept",
    render: ({ record }) => getDeptName(record.dept),
  },
  {
    title: "操作",
    fixed: "right",
    slotName: "action",
  },
];

// 获取科室列表
const fetchDeptList = async () => {
  try {
    const response = await getDeptList();
    if (response.code === 200 || response.code === 0) {
      deptList.value = response.data;
    } else {
      Message.error(response.message || "获取科室列表失败");
    }
  } catch (error) {
    console.error("获取科室列表错误:", error);
    Message.error("获取科室列表失败");
  }
};

// 获取组织架构列表
const fetchOrgList = async () => {
  try {
    const response = await getOrgList();
    if (response.code === 200 || response.code === 0) {
      orgTreeData.value = response.data;
    } else {
      Message.error(response.message || "获取组织架构列表失败");
    }
  } catch (error) {
    console.error("获取组织架构列表错误:", error);
    Message.error("获取组织架构列表失败");
  }
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await queryRoleList();
    if (response.code === 200 || response.code === 0) {
      roleList.value = response.data;
    } else {
      Message.error(response.message || "获取角色列表失败");
    }
  } catch (error) {
    console.error("获取角色列表错误:", error);
    Message.error("获取角色列表失败");
  }
};

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const params: UserQueryParams = {
      ...searchForm,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    };

    const response = await getUserList(params);

    if (response.code === 200 || response.code === 0) {
      tableData.value = response.data.rows;
      pagination.total = response.data.page.totalRow;
    } else {
      Message.error(response.message || "获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表错误:", error);
    Message.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 根据ID获取科室名称
const getDeptName = (deptId: number) => {
  const dept = deptList.value.find((item) => item.id === deptId);
  return dept ? dept.name : `未知科室(${deptId})`;
};

// 根据ID获取组织名称
const getOrgName = (orgId: number) => {
  const findOrgName = (orgs: OrgInfo[], id: number): string => {
    for (const org of orgs) {
      if (org.groupId === id) {
        return org.groupName;
      }
      if (org.children && org.children.length > 0) {
        const found = findOrgName(org.children, id);
        if (found) return found;
      }
    }
    return "未知组织";
  };
  const result = findOrgName(orgTreeData.value, orgId);
  return result || `未知组织(${orgId})`;
};

// 验证警号是否重复
const validatePoliceNum = async (policeNum: string, userId?: number) => {
  if (!policeNum) return;

  try {
    const response = await validUserByPoliceNum(policeNum, userId);
    if (response.code === 200 || response.code === 0) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    return false;
  }
  return true;
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchUserList();
};

// 重置搜索
const resetForm = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = Array.isArray(searchForm[key]) ? [] : "";
  });
  pagination.current = 1;
  fetchUserList();
};

// 分页变化
const onPageChange = (page: number) => {
  pagination.current = page;
  fetchUserList();
};

const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  searchForm.pageSize = pageSize;
  pagination.current = 1;
  fetchUserList();
};

// 新增用户
const handleAdd = async () => {
  formTitle.value = "新增用户";

  // 确保组织架构数据已加载
  if (orgTreeData.value.length === 0) {
    await fetchOrgList();
  }

  // 确保科室数据已加载
  if (deptList.value.length === 0) {
    await fetchDeptList();
  }

  Object.assign(formData, {
    name: "",
    iphone: "",
    role: 3,
    policeNum: "",
    group: undefined,
    dept: undefined,
  });
  formVisible.value = true;
};

// 编辑用户
const handleEdit = async (record: UserInfo) => {
  formTitle.value = "编辑用户";

  // 确保组织架构数据已加载
  if (orgTreeData.value.length === 0) {
    await fetchOrgList();
  }

  // 确保科室数据已加载
  if (deptList.value.length === 0) {
    await fetchDeptList();
  }

  Object.assign(formData, record);
  formVisible.value = true;
};

// 删除用户
const handleDelete = (record: UserInfo) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除用户 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        const response = await deleteUser(record.userId!);
        if (response.code === 200 || response.code === 0) {
          Message.success("删除成功");
          fetchUserList();
        } else {
          Message.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除用户错误:", error);
        Message.error("删除失败");
      }
    },
  });
};

// 批量删除
const handleBatchDelete = () => {
  console.log("批量删除", selectedRowKeys.value.length);
  if (selectedRowKeys.value.length === 0) {
    Message.warning("请选择要删除的用户");
    return;
  }

  Modal.confirm({
    title: "确认批量删除",
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个用户吗？`,
    onOk: async () => {
      try {
        const response = await batchDeleteUsers(selectedRowKeys.value);
        if (response.code === 200 || response.code === 0) {
          Message.success("批量删除成功");
          selectedRowKeys.value = [];
          fetchUserList();
        } else {
          Message.error(response.message || "批量删除失败");
        }
      } catch (error) {
        console.error("批量删除错误:", error);
        Message.error("批量删除失败");
      }
    },
  });
};

// 批量导入成功处理
const handleImportSuccess = (fileItem: FileItem) => {
  const { response } = fileItem;
  if (response.code !== 200 && response.code !== 0) {
    // 业务失败
    Message.error(response.message);
  } else {
    Message.success(response?.data);
    fetchUserList();
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    if (formTitle.value === "新增用户") {
      const response = await createUser(formData);
      if (response.code === 200 || response.code === 0) {
        Message.success("新增成功");
        formVisible.value = false;
        fetchUserList();
      } else {
        Message.error(response.message || "新增失败");
      }
    } else {
      const response = await updateUser(formData);
      if (response.code === 200 || response.code === 0) {
        Message.success("更新成功");
        formVisible.value = false;
        fetchUserList();
      } else {
        Message.error(response.message || "更新失败");
      }
    }
  } catch (error) {
    console.error("提交表单错误:", error);
    Message.error("操作失败");
  }
};

// 取消表单
const handleCancel = () => {
  formVisible.value = false;
};

// 页面加载时获取数据
onMounted(async () => {
  // 先加载科室和组织架构数据
  await Promise.all([fetchDeptList(), fetchOrgList(), fetchRoleList()]);

  // 再加载用户列表
  await fetchUserList();
});
</script>

<style lang="less" scoped>
.container {
  padding: 20px;
}
</style>
